$(document).ready(function() {
	Search.init();
});

Search = {};

Search.selectSum = 1;

Search.init = function() {
	var sortLink = $("#sortAddLink");
	
	Search.selectSum = $('.searchSortOption').length-1;
	if(Search.selectSum > 1)
		Search.addDeleteButton();
	
	$('#newSearchFieldLink').click(function(e){
		if(Search.selectSum < 5){
			Search.selectSum++;
			var template = $("#sorttemplate").clone();
			template.css('display', 'table-row');
			template.attr('id', 'sort'+Search.selectSum);
			template.find('select').attr('name', 'sort'+Search.selectSum);
			
			$('.searchSortOptionRow').find('.searchSortOptionDelete a').remove();
			template.find('.searchSortOptionDelete').html('<a href="#">x</a>');
			
			sortLink.before(template);
			Search.addDeleteButton();
			/*
			template.find('.searchSortOptionDelete').find('a').click(function(e){
				Search.removeFunction();
				return false;
			});
			*/
			if(Search.selectSum == 5){
				$('#newSearchFieldLink').css('display', 'none');
			}
		}
		
		return false;
	});
}

Search.removeFunction = function(){
	$("#sort"+Search.selectSum).remove();
	Search.selectSum--;
	if(Search.selectSum > 1){
		Search.addDeleteButton();
	}
	if(Search.selectSum < 5){
		$('#newSearchFieldLink').css('display', 'table-row');
	}
}

Search.addDeleteButton = function(){
	$("#sort"+Search.selectSum).find('.searchSortOptionDelete').html('<a href="#">x</a>');
	$("#sort"+Search.selectSum).find('.searchSortOptionDelete').find('a').click(function(e){
		Search.removeFunction();
		return false;
	});
}
